package com.harvey.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.harvey.entity.DataEntity;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @author Harvey
 * @date 2024-08-27 12:52
 **/
@Slf4j
@RestController
@RequestMapping("/export")
public class ExportController {

    @GetMapping("/xls")
    public String xls(HttpServletResponse response, @RequestParam(value = "contract_address", required = false) String contract_address,
                    @RequestParam(value = "start_timestamp", required = false) String start_timestamp,
                    @RequestParam(value = "end_timestamp", required = false) String end_timestamp,
                    @RequestParam(value = "start", required = false, defaultValue = "0") Integer start,
                    @RequestParam(value = "limit", required = false, defaultValue = "1000") Integer limit) throws UnsupportedEncodingException {
        String apiKey = "55947d3e-11af-48c3-82de-06b29a7e582f";
        String endpoint = "https://apilist.tronscanapi.com/api/token_trc20/transfers?start=" + start + "&limit=" + limit;

        if (StrUtil.isNotBlank(contract_address)) {
            endpoint += "&contract_address=" + contract_address;
        }
        if (StrUtil.isNotBlank(start_timestamp)) {
            endpoint += "&start_timestamp=" + DateUtil.parse(start_timestamp).getTime();
        }
        if (StrUtil.isNotBlank(end_timestamp)) {
            endpoint += "&end_timestamp=" + DateUtil.parse(end_timestamp).getTime();
        }
        log.info("请求地址：{}", endpoint);
        String result = HttpRequest.get(endpoint)
                .header("TRON-PRO-API-KEY", apiKey)
                .execute()
                .body();
        log.info("调用成功");
        List<DataEntity> rows = new ArrayList<>();
        try {
            JSONObject object = JSONUtil.parseObj(result);
            Object data = object.get("token_transfers");
            if (!Objects.isNull(data)) {
                log.info("调用结果不为空");
                JSONArray array = JSONUtil.parseArray(data);
                if (!array.isEmpty()) {
                    for (Object jsonObject : array) {
                        JSONObject obj = JSONUtil.parseObj(jsonObject);
                        DataEntity entity = new DataEntity();
                        DateTime timestamp = DateUtil.date(Long.valueOf(obj.get("block_ts").toString()));
                        entity.setTimestamp(DateUtil.formatDateTime(timestamp));
                        entity.setFromAddress(obj.get("from_address").toString());
                        entity.setToAddress(obj.get("to_address").toString());
                        entity.setToAddressIsContract(obj.get("toAddressIsContract").toString());
                        BigDecimal quant = new BigDecimal(obj.get("quant").toString());
                        BigDecimal amount = quant.divide(new BigDecimal("10").pow(18), 3, RoundingMode.HALF_UP);
                        entity.setAmount(amount.toString());
                        entity.setResult(obj.get("finalResult").toString());
                        rows.add(entity);
                    }
                }
            }
            log.info("取出结果: {}", rows);
        } catch (Exception e) {
            log.error("返回结果不正确", e);
        }
        if (!rows.isEmpty()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("导出结果", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            try {
                log.info("开始导出......");
                EasyExcel.write(response.getOutputStream())
                        .head(DataEntity.class)
                        .excelType(ExcelTypeEnum.XLSX)
                        .sheet(fileName)
                        .doWrite(rows);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("导出成功{}条数据", rows.size());
        } else {
            log.info("数据为空，导出失败");
            return "数据为空，导出失败";
        }
        return "导出成功"+rows.size()+"条数据";
    }
}
